/**
 * Created by wurenjie on 15/5/4.
 */
var usr_username="";
$(function(){
    userInit();
    $.get("/getrandomnavimage.json",{},function(data){
        $("#nav-img").attr("src", data);
    });
    $(".navigation-index li").bind("mouseenter",function(e){
        $(this).css("background-color","red");
    });
    $(".navigation-index li").bind("mouseleave",function(e){
        $(this).css("background-color","#F2F2F2");
    });
    $(".nav ul li").bind("mouseenter",function(e){
        $(this).css("background-color","red");
        $(this).children("ul").fadeIn(250);

    });
    $(".nav ul li").bind("mouseleave",function(e){
        $(this).css("background-color","black");
        $(this).children("ul").fadeOut(250);

    });
    $(".scrollUp").bind("mouseenter",function(e){
        $(this).css("background-color","#333");

    });
    $(".scrollUp").bind("mouseleave",function(e){
        $(this).css("background-color","#777");

    });
    $(".scrollUp").click(function(){
        $("html,body").animate({scrollTop:0});
    })
    $("#username").blur(function(){
        var username=$("#username").val();
        if(username!==""){
            $("#username").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6)","border-color":"rgba(102,175,233,1)","trasition":"border-color ease-in-out 0.15s"});
            $("#register-username-error").hide();
        }
        else{
            $("#username").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
            $("#register-username-error").show();
        }
    });
    $("#password").blur(function(){
        var password=$("#password").val();
        if(/^[A-Za-z0-9]{6,20}$/.test(password)){
            $("#password").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6)","border-color":"rgba(102,175,233,1)","trasition":"border-color ease-in-out 0.15s"});
            $("#register-password-error").hide();
        }
        else{
            $("#password").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
            $("#register-password-error").show();
        }
    });
    $("#email").blur(function(){
        var email=$("#email").val();
        if(/^[A-Za-z0-9_.-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(email)){
            $("#email").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6)","border-color":"rgba(102,175,233,1)","trasition":"border-color ease-in-out 0.15s"});
            $("#register-email-error").hide();
        }
        else{
            $("#email").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
            $("#register-email-error").show();
        }

    });
    $("#user-register").click(function(){
       checkRegister();
    });
    $("#login_form").submit(function(){
        event.preventDefault();
        var username=$("#login-username").val();
        var password=$("#login-password").val();
    });
    $("#titleForm").submit(function(){
        event.preventDefault();
        addMessage();
    });
    comment_scrollUp();
    $(document).on("click",".reply",function(){
        $(this).parents(".sub-frame").children(".sub-container").toggle();
        $(this).parents(".sub-frame").find("#sub-sayArea").val("").focus();

    })
    $(document).on("click",".reply-infloor",function(){
        var father_name=$(this).parents(".sub-saylist").find("p strong").html().replace(/(^\s*)|(\s*$)/g, "");
        $(this).parents(".sub-frame").children(".sub-container").toggle();
        $(this).parents(".sub-frame").find("#sub-sayArea").val("回复 "+father_name+": ").focus();

    })
    $(".insert-image").click(function(){
        popover_open("50","50");
    });
    $(document).on("click","#sub-image",function(){
        popover_open("50","50");
    })
    $(document).on("click","#sub-submit",function(){
        popover_open_info("发布成功");
    })
    $(document).on("click",".close",function(){
        popover_close();
    })
    //wiki导航toggle
    $("#wikiEdit").click(function(e){
        e.preventDefault();
        $(this).tab('show');
        $("#wikiEdit-textarea").show();
    });
    $("#wikiPreview").click(function(e){
        e.preventDefault();
        $(this).tab('show');
        $("#wikiEdit-textarea").hide();
    });
    $("#wikiImage").click(function(){
        popover_open("50","50");
    });
    $("#login-btn").click(function(){
        checkLogin();
    })
    $("#insert-image-confirm").click(function(){
        var filename=$("#filename").val()
        if(/^http[s]{0,1}:\/\/.+\.(jpg|jpeg|gif|png)$/.test(filename)){
            var wikiArea=$("#wikiEdit-textarea").val();
            wikiArea+="\n[["+filename+"]]\n";
            $("#wikiEdit-textarea").val(wikiArea);
            //$("#sub-sayArea").val(wikiArea);
            //$("#sayTxt").val(wikiArea);
            popover_close();
        }
        else{
            $("#insert-image-null").show().html("图片地址不合法").fadeOut(2000);
            return 0;
        }
    });
    $(".search-input").bind('keypress',function(e){
        var input=$("#search-input").val();
        if(e.keyCode=="13"){
            location.href="/wiki/"+input;
        }
    })

});
function upload(token, key, upapi, domain){
    console.log("upload");
    var formData = new FormData();
    formData.append('key', key);
    formData.append('token', token);
    formData.append('file', $("#localImg-upload").get(0).files[0]);
    console.log(formData);
    $.ajax({
        url: upapi,
        contentType: false,
        data: formData,
        processData: false,
        type: 'POST',
        success: function(data){
            var resourceUrl = domain + data.key;
            $("#st").html("上传成功。");
            $("#filename").val(resourceUrl);
            $(".input-file").fadeIn(300);
        },
        error: function(xhr, error, obj){
            var data = JSON.parse(xhr.responseText);
            $("#st").html("上传失败：" + data.error);
        }
    });
}
function addMessage(){
    var sayTxt = $("#wikiEdit-textarea").val();
    var title = $(".comment-title-input").val();
    if(title==""){
        $("#message").show().html("标题不能为空噢").fadeOut(1200);
        return false;
    }
    if(sayTxt==""){
        $("#message").show().html("你总得说点什么吧.").fadeOut(1200);
        return false;
    }

    $.post("/forum/newthread.json",{
        title:title,
        content:sayTxt
    },function(data){
        data=JSON.parse(data);
        if(data.result=="error"){
            popover_open_info(data.info)
        }
        if(data.result=="success"){
            console.log("dwd");
            var msg='<div class="thread" id="thread">'+
                '<div class="reply-number" id="reply-number">33</div>'+
            '<div class="thread-title"><a><h2>dd</h2></a></div>'+
            '<div class="po-reply-name" id="po-name"><a>up</a></div>'+
            '<div class="clear"></div>'+
            '<div class="last-reply-time" id="last-reply-time">22-11</div>'+
                '</div>';
            $(".threadWrap").append(msg);
            popover_open_info("发帖成功");
            setTimeout(function(){
                location.href="/thread/"+data.threadid;
            },1000);
        }
    });
}
function userInit(){
    $.getJSON("/user/isLogin.json",{},function(data){
        if(data.status===true){
            $("#nav-register").html(data.username);
            $("#nav-register").attr("href","/home");
            $("#nav-login").html("注销");
            $("#nav-login").attr("href","javascript:;")
            $("#nav-login").click(function(){
                loginout();
            })
        }
        else if(data.status===false){
            $("#nav-register").html("注册");
            $("#nav-register").attr("href","/register");
            $("#nav-login").html("登录");
        }
    })
}
//滚动条在comment区时上移
function comment_scrollUp(){
    var comment_height=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    $(window).scroll(function(){
        var this_scrollTop=$(this).scrollTop();
        if(this_scrollTop>comment_height){
            $(".scrollUp").fadeIn(500);
        }
        else{
            $(".scrollUp").fadeOut(500);
        }
    });
}
//模态框
function popover_open(x,y){
    /*var left=50-x/2;
    left=left+"%";
    var widthX=x+"%";
    var heightY=y+"%";
    $(".theme-popover").css({"width":widthX,"height":heightY,"left":left});*/
    $(".theme-popover-mask").fadeIn(100);
    $(".theme-popover").slideDown(200);
    $(".insert-image-container").show();
}
function popover_open_info(string){
    $(".theme-popover-mask").fadeIn(100);
    $(".theme-popover").slideDown(200);
    $(".theme-message").html(string);
}
function popover_close(){
    $(".theme-popover-mask").fadeOut(100);
    $(".theme-popover").slideUp(200);
    $(".insert-image-container").hide();
    $(".theme-message").html("");
    $("#filename").val('');
    $("#st").html("");
}

function checkLogin(){
    var username=$("#login-username").val();
    var password=$("#login-password").val();
    if(username==""){
        $("#login-username").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
        $("#login-username-error").show();
        return 0;
    }
    if(!/^[A-Za-z0-9]{6,20}$/.test(password)){
        $("#login-password").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
        $("#login-password-error").show();
        return 0;
    }
    $.post("/user/login.json",{
        username:username,
        password:password
    },function(data){
        data=JSON.parse(data);
        usr_username=data.username;
        if(data.result=="success"){
            popover_open_info("欢迎回来"+username+"<br>两秒后自动跳转");
            setTimeout(function(){
                location.href="/home";
            },2000);
            $("#nav-user").html(username);
            $("#nav-register").html(username);
            $("#nav-login").html(username);
        }
        else{
            popover_open_info("登录失败:"+data.info);
        }

    });
}
function checkRegister(){
    var username=$("#username").val();
    var password=$("#password").val();
    var email=$("#email").val();
    if(username==""){
        $("#username").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
        $("#register-username-error").show();
        return 0;
    }
    if(!/^[A-Za-z0-9]{6,20}$/.test(password)){
        $("#password").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
        $("#register-password-error").show();
        return 0;
    }
    if(!/^[A-Za-z0-9_.-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(email)){
        $("#email").css({"box-shadow":"inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(255,0,0,.5)","border-color":"red","trasition":"border-color ease-in-out 0.15s"});
        $("#register-email-error").show();
        return 0;
    }
    $.post("/user/register.json",{
        "username":username,
        "password":password,
        "email":email
    },function(data){
        data=JSON.parse(data);
        if(data.result=="success"){
            popover_open_info("注册成功<br>两秒后自动跳转");
            setTimeout(function(){
                location.href="/login";
            },2000);
        }
        else{
            popover_open_info("注册失败:"+data.info);
        }

    });
}
function loginout(){
    $.getJSON("/user/logout.json",{},function(){
        popover_open_info("要记得伦家噢<br>两秒后自动跳转");
        setTimeout(function(){
            window.location.reload();
        },2000);
    })
}
function change(e){
    var filename = $("#localImg-upload").get(0).files[0].name;
    filename = filename.substring(0, filename.lastIndexOf("."));
    $.getJSON("/getuploadtoken.json",{
        "input" : filename
    },function(data){
        $("#st").html("正在上传中，请稍候。。。");
        console.log("lalala");
        upload(data.token, data.key, data.upapi, data.domain);
    });
    /*var src= e.target||window.event.srcElement;
    var route=src.value;
    var filename=route.substring(route.lastIndexOf('\\')+1,route.lastIndexOf('.') );
    var substring=route.substring(route.lastIndexOf('.')+1);
    if(substring=='jpg'||substring=='png'||substring=='jpeg'||substring=='gif'||substring=='bmp'){
        $("#filename").val(filename);
    }
    else{
        alert("您传的不是图片");
        return 0;
    }*/
}